#!/bin/zsh

#  deploy.sh
#  
#
#  Created by 龚杰洪 on 2023/10/30.
#  

git pull
name=studio_web
time=$(date +"%Y_%m_%d_%H_%M")
new_name="${name}_${time}"
if [ "$1" = "test_ali" ] || [ "$1" = "prod_ym" ]; then
    work_path=$(pwd)

    echo '删除'$name'dist文件'
    rm -rf dist

    echo '开始编译'
    yarn install
    yarn add sass
    npm run $1
    echo '编译完成'

    echo '开始打包...删除文件夹'
    rm -rf /tmp/$name/

    echo '开始打包...创建文件夹'
    mkdir /tmp/$name/

    echo '开始打包...拷贝文件'
    cp -rf dist/ /tmp/$name/dist/
    cd /tmp/

    echo '开始打包'
    gtar -czvf $name.tar.gz $name/

    mv $name.tar.gz ${work_path}

    # 回到当前工程目录
    cd ${work_path}

    echo '上传文件'
    if [ "$1" = "test_ali" ]; then
        scp -i ~/Documents/ssh_key/cd-yuanmengkongjian.pem $name.tar.gz root@47.108.198.188:/applications/nginx/html/
    elif [ "$1" = "prod_ym" ]; then
        scp -i ~/Documents/ssh_key/tan-metayuanmeng-shenzhen.pem $name.tar.gz root@120.76.117.113:/applications/nginx/html/
    fi
    echo '上传完成'

    # 回到当前工程目录
    cd ${work_path}

    echo '服务器执行重启服务脚本'
    if [ "$1" = "test_ali" ]; then
        ssh -i ~/Documents/ssh_key/cd-yuanmengkongjian.pem root@47.108.198.188 "cd /applications/nginx/html/; mv $name backup/$name/$new_name; tar -zxvf $name.tar.gz;"
    elif [ "$1" = "prod_ym" ]; then
        ssh -i ~/Documents/ssh_key/tan-metayuanmeng-shenzhen.pem root@120.76.117.113 "cd /applications/nginx/html/; mv $name backup/$name/$new_name; tar -zxvf $name.tar.gz;"
    fi

    # rm $name
    rm $name.tar.gz

    echo 'All Done' && echo $time $name $1 >> /Users/gongjiehong/Documents/gopath/src/publish_log/association-admin.log 
else
    echo '环境必须是test_ali或prod_ym, 执行 ./deploy test_ali 或 ./deploy prod_ym'
fi
